import { Config } from '@/store'
import axios, { AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import { getToken } from './auth'

const request = axios.create()

// 请求拦截器
request.interceptors.request.use(config => {
  const Config = getToken('unify-config') as Config
  const DefaultToken = 'Basic dHJ1Y2stY2xpZW50OnRydWNrLXNlY3JldA=='
  const Token = getToken()
  config.baseURL = Config?.apiHostMain
  if (!config.headers) config.headers = {}
  config.headers.Authorization = Token ? `Bearer ${Token}` : DefaultToken
  return config
}, err => {
  return Promise.reject(err)
})

// 响应拦截器
request.interceptors.response.use(res => {
  if (res.data.code === -1) {
    ElMessage({
      type: 'error',
      message: res.data.msg,
      duration: 2000,
      showClose: true
    })
    return Promise.reject(res)
  }
  return Promise.resolve(res)
}, err => {
  if (err.response.status === 401) {
    ElMessage({
      type: 'error',
      message: '登录状态已过期，请重新登录',
      duration: 2000,
      showClose: true,
      onClose () {
        // const config = getToken('unify-config')
        // window.location.href = config.redirectUrl
      }
    })
    return
  }
  const message = err.response.data.msg
  ElMessage({
    type: 'error',
    message: message || `接口请求错误，状态：${err.response.status}`,
    duration: 2000,
    showClose: true
  })
  return Promise.reject(err)
})

export default <T = any>(config: AxiosRequestConfig) => {
  return request(config).then(res => {
    return res.data as T
  })
}
